//
//  LocationManager.m
//  StormWatch
//
//  Created by 王岩 on 2024/9/26.
//

#import "LocationManager.h"
#import <AFNetworking/AFNetworking.h>
@interface LocationManager () <CLLocationManagerDelegate>{
    NSString * cityName;
    CGFloat lat, lon;
}
@property (nonatomic, strong) CLLocationManager * locationManager;

/* <#note#> */
@property (nonatomic, strong) NSDictionary  * nowWeatherInfo;

@end

@implementation LocationManager


SingletonM;

+ (BOOL)getLocationEnable {
    return [CLLocationManager locationServicesEnabled];
}

- (void)startUpdateLocation {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        DDLogDebug(@"开始更新天气数据");
        [self.locationManager startUpdatingLocation];
    });
}

-(CLLocationManager *) locationManager
{
    if (_locationManager == nil)
    {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        _locationManager.pausesLocationUpdatesAutomatically = NO;
        [_locationManager setActivityType:CLActivityTypeFitness];
//        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9)
//        {
//            _locationManager.allowsBackgroundLocationUpdates = YES;
//        }
//        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
//        {
//            //使用期间
//            [_locationManager requestAlwaysAuthorization];
//        }
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.delegate =  self;
    }
    return _locationManager;
}

#pragma mark - CLLocationManagerDelegate
// 用户的位置更新之后调用
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    CLLocation *location = locations.firstObject;
    NSLog(@"%f", location.coordinate.longitude);
    NSLog(@"%f", location.coordinate.latitude);
    lat = location.coordinate.latitude;
    lon = location.coordinate.longitude;
    
    if (lat && lon ) {
        [self getCityInfo];
    }
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
}

// 授权状态发生改变时调用
// 第一次弹出请求定位权限会执行该代码块 用户如果点击 "不允许"  执行"定位开启，但被拒", 若点击 "允许" 执行 获取前后台定位授权 或者 获取前后台定位授权 如果在设置 设置隐私 定位服务 "永不" 则执 "行定位开启，但被拒"
// 注意:在设置点击了"永不"之后不返回应用在切换后台跟前台选项是不会执行该代理方法的 当返回应用之后 才会对做出的改变执行代理方法
// 关闭定位服务会执行 定位关闭，"不可用" 系统默认弹出弹框 提示用户去设置中打开定位服务选项
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
            // 用户还未决定
        case kCLAuthorizationStatusNotDetermined:
        {
            NSLog(@"用户还未决定");
            
            break;
        }
            // 访问受限
        case kCLAuthorizationStatusRestricted:
        {
            NSLog(@"访问受限");
            break;
        }
            // 定位关闭时和对此APP授权为never时调用
        case kCLAuthorizationStatusDenied:
        {
            // 定位是否可用（是否支持定位或者定位是否开启）
            if([CLLocationManager locationServicesEnabled])
            {
                NSLog(@"定位开启，但被拒");
            }else
            {
                NSLog(@"定位关闭，不可用, 请在设置中打开定位服务选项");
            }
            //            NSLog(@"被拒");
            break;
        }
            // 获取前后台定位授权
        case kCLAuthorizationStatusAuthorizedAlways:
            //        case kCLAuthorizationStatusAuthorized: // 失效，不建议使用
        {
            NSLog(@"获取前后台定位授权");
//            [self startUpdateLocation];
            break;
        }
            // 获得前台定位授权
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            NSLog(@"获得前台定位授权");
//            [self startUpdateLocation];
            break;
        }
    }
}

- (void)getCityInfo {
    NSString * url = [NSString stringWithFormat:@"https://geoapi.qweather.com/v2/city/lookup?location=%.2f,%.2f&key=715fe233158841dcbe10e4ba73ffe32f",lon, lat];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary * dic = responseObject;
            if ([dic[@"code"] isEqualToString:@"200"]) {
                NSDictionary * location = dic[@"location"][0];
                
                self->cityName = [NSString stringWithFormat:@"%@%@",location[@"adm2"],location[@"name"]];
                
                [self getWeatherInfo];
            }else {
                NSLog(@"城市数据获取失败");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)getWeatherInfo {
    
    NSString * url = [NSString stringWithFormat:@"https://devapi.qweather.com/v7/weather/now?location=%.2f,%.2f&key=715fe233158841dcbe10e4ba73ffe32f",lon, lat];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary * dic = responseObject;
            if ([dic[@"code"] isEqualToString:@"200"]) {
                
                self.nowWeatherInfo = dic[@"now"];
                
               
                [self getWeather2];
            }else {
                NSLog(@"天气数据获取失败");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)getWeather2 {
    NSString * url = [NSString stringWithFormat:@"https://devapi.qweather.com/v7/weather/7d?location=%.2f,%.2f&key=715fe233158841dcbe10e4ba73ffe32f",lon, lat];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary * dic = responseObject;
            if ([dic[@"code"] isEqualToString:@"200"]) {
                NSArray * daily = dic[@"daily"];
                [self sendNowWeather:daily  ];
                
            }else {
                NSLog(@"天气数据获取失败");
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}


- (void)sendNowWeather:(NSArray *)weathers {
    NSMutableArray * dataArray = [NSMutableArray array];
    // 地址信息
    NSData * cityData = [cityName mj_JSONData];
    // 转换为Byte数组
    Byte *byteArray = (Byte *)malloc(cityData.length);
    [cityData getBytes:byteArray length:cityData.length];
    
    [dataArray addObject:@(sizeof(byteArray))];
    for (int i = 0; i < sizeof(byteArray) ; i ++) {
        [dataArray addObject:@(byteArray[i])];
    }
    
    // 时间戳
    NSString * obsTime = [self.nowWeatherInfo[@"obsTime"] substringWithRange:NSMakeRange(0, 10)];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"YYYY-MM-dd"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSDate* date = [formatter dateFromString:obsTime]; //------------将字符串按formatter转成nsdate
    long value = (long)[date timeIntervalSince1970];
    unsigned char byte1 = (value & 0xff000000)>>24;
    unsigned char byte2 = (value & 0xff0000)>>16;
    unsigned char byte3 = (value & 0xff00)>>8;
    unsigned char byte4 = (value & 0xff);
    
    [dataArray addObject:@(byte1)];
    [dataArray addObject:@(byte2)];
    [dataArray addObject:@(byte3)];
    [dataArray addObject:@(byte4)];
 
    // 温度
    NSString * temp = self.nowWeatherInfo[@"temp"];
    if (temp.intValue > 0) {
        unsigned char byte = ((temp.intValue & 0xff) & 0x7f);
        [dataArray addObject:@(byte)];
    }else {
        unsigned char byte = ((temp.intValue & 0xff) | 0x80);
        [dataArray addObject:@(byte)];
    }
    // 最高温
    NSString * tempMax = weathers[0][@"tempMax"];
    if (tempMax.intValue > 0) {
        unsigned char byte = ((tempMax.intValue & 0xff) & 0x7f);
        [dataArray addObject:@(byte)];
    }else {
        unsigned char byte = ((tempMax.intValue & 0xff) | 0x80);
        [dataArray addObject:@(byte)];
    }
     // 最低温
    NSString * tempMin = weathers[0][@"tempMin"];
    if (tempMin.intValue > 0) {
        unsigned char byte = ((tempMin.intValue & 0xff) & 0x7f);
        [dataArray addObject:@(byte)];
    }else {
        unsigned char byte = ((tempMin.intValue & 0xff) | 0x80);
        [dataArray addObject:@(byte)];
    }
    
    // 天气类型
    int type = [self getWeatherType:[self.nowWeatherInfo[@"icon"] intValue]];
    unsigned char typebyte = (type & 0xff);
    [dataArray addObject:@(typebyte)];
    
//    湿度
    int humidity = [self.nowWeatherInfo[@"humidity"] intValue];
    unsigned char humiditybyte = (humidity & 0xff);
    [dataArray addObject:@(humiditybyte)];
    
//    降雨量
    int precip = [[(NSString *)self.nowWeatherInfo[@"precip"] componentsSeparatedByString:@"."].firstObject intValue];
    unsigned char precipbyte = (precip & 0xff);
    [dataArray addObject:@(precipbyte)];
    
    // 风速
    int windSpeed = [self.nowWeatherInfo[@"windSpeed"] intValue];
    unsigned char windSpeedbyte = (windSpeed & 0xff);
    [dataArray addObject:@(windSpeedbyte)];
    
    // 紫外线等级
    int uvIndex = [weathers[0][@"uvIndex"] intValue];
    unsigned char uvIndexbyte = (uvIndex & 0xff);
    [dataArray addObject:@(uvIndexbyte)];
    
    
    [[StormCommandTool sharedInstance] writeStormCommand:Command_NowWeather Value:dataArray reBack:^(NSString * _Nonnull backData) {
        if ([backData hasSuffix:@"00"]) {
            [self send7DaysWeather:weathers];
        }
    }];
  
}

- (void)send7DaysWeather:(NSArray *)list {
    NSMutableArray * dataArray = [NSMutableArray array];
    // 地址信息
    NSData * cityData = [cityName mj_JSONData];
    // 转换为Byte数组
    Byte *byteArray = (Byte *)malloc(cityData.length);
    [cityData getBytes:byteArray length:cityData.length];
    
    [dataArray addObject:@(sizeof(byteArray))];
    for (int i = 0; i < sizeof(byteArray) ; i ++) {
        [dataArray addObject:@(byteArray[i])];
    }
    
    for (int i = 0; i < list.count; i ++) {
        NSDictionary * weatherDic = list[i];
        // 时间戳
        NSString * obsTime = weatherDic[@"fxDate"];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
        NSDate* date = [formatter dateFromString:obsTime]; //------------将字符串按formatter转成nsdate
        long value = (long)[date timeIntervalSince1970];
        unsigned char byte1 = (value & 0xff000000)>>24;
        unsigned char byte2 = (value & 0xff0000)>>16;
        unsigned char byte3 = (value & 0xff00)>>8;
        unsigned char byte4 = (value & 0xff);
        
        [dataArray addObject:@(byte1)];
        [dataArray addObject:@(byte2)];
        [dataArray addObject:@(byte3)];
        [dataArray addObject:@(byte4)];
     
     
        // 最高温
        NSString * tempMax = weatherDic[@"tempMax"];
        if (tempMax.intValue > 0) {
            unsigned char byte = ((tempMax.intValue & 0xff) & 0x7f);
            [dataArray addObject:@(byte)];
        }else {
            unsigned char byte = ((tempMax.intValue & 0xff) | 0x80);
            [dataArray addObject:@(byte)];
        }
         // 最低温
        NSString * tempMin = weatherDic[@"tempMin"];
        if (tempMin.intValue > 0) {
            unsigned char byte = ((tempMin.intValue & 0xff) & 0x7f);
            [dataArray addObject:@(byte)];
        }else {
            unsigned char byte = ((tempMin.intValue & 0xff) | 0x80);
            [dataArray addObject:@(byte)];
        }
        
        // 天气类型
        int type = [self getWeatherType:[weatherDic[@"iconDay"] intValue]];
        unsigned char typebyte = (type & 0xff);
        [dataArray addObject:@(typebyte)];
        
    //    湿度
        int humidity = [weatherDic[@"humidity"] intValue];
        unsigned char humiditybyte = (humidity & 0xff);
        [dataArray addObject:@(humiditybyte)];
        
    //    降雨量
        int precip = [[(NSString *)weatherDic[@"precip"] componentsSeparatedByString:@"."].firstObject intValue];
        unsigned char precipbyte = (precip & 0xff);
        [dataArray addObject:@(precipbyte)];
        
        // 风速
        int windSpeed = [weatherDic[@"windSpeedDay"] intValue];
        unsigned char windSpeedbyte = (windSpeed & 0xff);
        [dataArray addObject:@(windSpeedbyte)];
        
        // 紫外线等级
        int uvIndex = [weatherDic[@"uvIndex"] intValue];
        unsigned char uvIndexbyte = (uvIndex & 0xff);
        [dataArray addObject:@(uvIndexbyte)];
        
    }
  
    [[StormCommandTool sharedInstance] writeStormCommand:Command_DelayWeather Value:dataArray reBack:^(NSString * _Nonnull backData) {
        if ([backData hasSuffix:@"00"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60*60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.locationManager startUpdatingLocation];
            });
        }
    }];
    
}

- (int)getWeatherType:(int)type {
    if (type >= 100 && type <= 110) {
        return type - 100;
    }
    if (type >= 150 && type <= 160) {
        return type - 150;
    }
    if (type >= 300 && type <= 320) {
        return type - 295;
    }
    if (type >= 350 && type <= 352) {
        return type - 245;
    }
    if (type == 399) {
        return 24;
    }
    if (type >= 400 && type <= 410) {
        return type - 375;
    }
    if (type >= 456 && type <= 458) {
        return type - 375;
    }
    if (type == 499) {
        return 36;
    }
    if (type >= 500 && type <= 504) {
        return type - 463;
    }
    if (type >= 507 && type <= 515) {
        return type - 465;
    }
    if (type == 900) {
        return 51;
    }
    if (type == 901) {
        return 52;
    }
    return 255;
}

@end
